import java.math.BigInteger
import java.security.MessageDigest
import java.util.*
import javax.xml.bind.DatatypeConverter


object Md5Utils {

    fun sha1(input: String) = hashString("SHA-1", input)

    @JvmStatic

    fun md5(input: String) = hashString("MD5", input)

    private fun hashString(type: String, input: String): String {
        val bytes = MessageDigest
            .getInstance(type)
            .digest(input.toByteArray())
        return DatatypeConverter.printHexBinary(bytes).uppercase(Locale.getDefault())
    }

    @JvmStatic
    fun Md5WithToken(plainText: String, token: String): String {
        val md = MessageDigest.getInstance("MD5")
        md.update((plainText + token).toByte())
        val b = md.digest()
        var i: Int
        val buf = StringBuffer("")
        for (offset in b.indices) {
            i = b[offset].toInt()
            if (i < 0) i += 256
            if (i < 16) buf.append("0")
            buf.append(Integer.toHexString(i))
        }
        return buf.toString()

    }
}

public fun String.toMD5(): String {
    val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
    return bytes.toHex()
}

public fun ByteArray.toHex(): String {
    return joinToString("") { "%02x".format(it) }
}

public fun String.sha256(): String {
    val md = MessageDigest.getInstance("SHA-256")
    return BigInteger(1, md.digest(toByteArray())).toString(16).padStart(32, '0')
}

fun main() {
    println(Md5Utils.md5("Assa"))

}